<?php

/***
 * Jeżeli nie podłączy się do bazy to aplikacja kończy działanie!!!!! 
 */
class DBConnection {
	private static $instance;

	private $dbh;
	
	private static $host;
	private static $login;
	private static $pass;
	private static  $db_name;

	private function __construct($host, $login, $pass, $db_name) {
		try {
			$conn_url='mysql:host='.$host.';dbname='.$db_name.'';
			$this->dbh=new PDO($conn_url,$login,$pass);						
			$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);		
		} catch (PDOException $e) {			
			print "Error: ".$e->getMessage().'<br />';
			die();
		}		
	}

	public function exec_param_transaction($query, $params) {
		try{			
			$this->dbh->beginTransaction();			
			$stmt=$this->dbh->prepare($query);
			$stmt->execute($params);
			$this->dbh->commit();					
		} catch (Exception $e) {
  			$this->dbh->rollBack();
  			echo "Failed: " . $e->getMessage() . "<br />";
		}
	}
	
	public function exec_queries_in_transaction($queries, $params) {
		try{			
			$this->dbh->beginTransaction();		
			for($i = 0; $i < count($queries); ++$i) {
				$stmt = $this->dbh->prepare($queries[$i]);
				$stmt->execute($params[$i]);
			}
			$this->dbh->commit();					
		} catch (Exception $e) {
  			$this->dbh->rollBack();
  			echo "Failed: " . $e->getMessage() . "<br />";
		}
	}
	
	public function exec_query($query, $params) {
		try {
			$stmt = $this->dbh->prepare($query);				
			$stmt->execute($params);
			$result = $stmt->rowCount();		
		} catch (PDOException $e) {			
			throw new PDOException($e->getMessage(),0,$e);
		}
		return $result;		
	}
	
	public function exec_select_query($query, $params, $append=null) {
		try{
			if (isset($append)) {
				$query=$query.$append;
			}
			$stmt=$this->dbh->prepare($query);				
			$stmt->execute($params);
			$result=$stmt->fetchAll();		
		
		}catch (PDOException $e) {			
			throw new PDOException($e->getMessage(),0,$e);
		}
		return $result;		
	}
	
	public function exec_count_select($query) {
		try{
			$stmt=$this->dbh->prepare($query);			
			$stmt->execute();
			$result=$stmt->fetchAll();		
		
		}catch (PDOException $e) {
			echo "Error: ".$e->getMessage().'<br />';
			throw new PDOException($e->getMessage(),0,$e);
		}
		return sizeof($result);
	}
	
	public function getDBH() {
		return $this->dbh;
	}

	public static function  getInstance() {		
		if (!isset(self::$instance)) {
			$className = __CLASS__;
			self::$instance = new $className(self::$host,self::$login,self::$pass, self::$db_name);
		}
		return self::$instance;
	}

	public static function  setDBName($name) {
		self::$db_name=$name;
	}
	
	public static function  setLogin($login) {
		self::$login=$login;
	}
	
	public static function  setPass($pass) {
		self::$pass=$pass;
	}

	public static function  setHost($host) {
		self::$host=$host;
	}
}

?>